﻿using System;
using System.IO;
using System.Threading.Tasks;
using UnityEngine.Networking;

/// <summary>
/// 更新资源句柄
/// </summary>
public class UpdateDownloadHandler : DownloadHandlerScript
{
    public UnityWebRequest OwnerRequest;

    private FileStream m_FileStream;

    private long m_TotalLen;

    Task mWrite;

    /// <summary>下载文件大小</summary>
    public long totalLength {
        get {
            return m_TotalLen;
        }
    }

    public double Progress;
    public double mLoadedLen = 0;
    public double mLoadedOldLen = 0;

    public event Action<FileDownloadEventArgs> OnStarted;

    public event Action<FileDownloadEventArgs> OnDataReceived;

    public event Action<FileDownloadEventArgs> OnCompleted;

    private FileDownloadEventArgs m_DownloadArgs;

    public string LoadPath;
    public UpdateDownloadHandler(string filePath)
    {
        LoadPath = filePath;

        m_FileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        //m_FileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        m_DownloadArgs = new FileDownloadEventArgs(this);

        m_TotalLen = GetLength();
        m_FileStream.Seek(m_TotalLen,SeekOrigin.Begin);
    }

    public long GetLength()
    {
        return m_FileStream.Length;
    }

    public void Seek(long offset, SeekOrigin origin)
    {
        m_FileStream.Seek(offset, origin);
    }

    protected override void ReceiveContentLength(int contentLength)
    {
        base.ReceiveContentLength(contentLength);
        m_TotalLen = contentLength + m_TotalLen;
        OnStarted?.Invoke(m_DownloadArgs);
    }

    protected override bool ReceiveData(byte[] data, int dataLength)
    {
        OnDataReceived?.Invoke(m_DownloadArgs);
        mWrite = m_FileStream.WriteAsync(data, 0, dataLength);
        mLoadedLen += dataLength;

        Progress = mLoadedLen / m_TotalLen;

        return base.ReceiveData(data,dataLength);
    }


    protected override void CompleteContent()
    {
        base.CompleteContent();
      

        if(mWrite != null && mWrite.IsCompleted)
        {
            //DoComplete();
        }
        else if(mWrite != null)
        {

        }
        else
        {
            //DoComplete();
        }
    }

    public bool IsComplete()
    {
        return mWrite != null && mWrite.IsCompleted;
    }

    public void Update()
    {
        if (mWrite.IsCompleted)
        {
            DoComplete();
        }
    }

    public void DoComplete()
    {
        if(OnCompleted != null)
            OnCompleted?.Invoke(m_DownloadArgs);

        if (m_FileStream != null)
        {
            m_FileStream.Flush();
            m_FileStream.Dispose();
        }
        m_FileStream = null;
        OnCompleted = null;
    }

    public new void Dispose()
    {
       
        try
        {
            if (m_FileStream != null)
            {
                m_FileStream.Flush();
                m_FileStream.Dispose();
            }

            m_FileStream = null;
            OnCompleted = null;
        }
        catch { }

        base.Dispose();
    }
}

public class FileDownloadEventArgs : EventArgs
{
    public UpdateDownloadHandler downloadHandler { get; }

    public FileDownloadEventArgs(UpdateDownloadHandler handler)
    {
        downloadHandler = handler;
    }
}